<?php

class ActionPending_List extends BaseAction
{
    public function run()
    {
        if ( Yii::app()->request->getIsPostRequest())
        {
            $iTariffPlanBuyLotId = Yii::app()->request->getParam('tariff_plans_buy_lot_id');
            $oTariffPlanBuyLots = TariffPlanBuyLots::model()->findByPk($iTariffPlanBuyLotId);
	    

            if($oTariffPlanBuyLots)
            {
                $oTariffPlan = TariffPlan::model()->findByPk($oTariffPlanBuyLots->tariff_plan_id);

                if($oTariffPlan)
                {
                    $sDoRequest = Yii::app()->request->getParam('do');
                    
                    if ( $sDoRequest == 'approve' )
                    {
                        $oTariffPlanBuyLots->date_approved = date('Y-m-d H:i:s');
                        $oTariffPlanBuyLots->status = 'approved';
                        $oTariffPlanBuyLots->save();

                        $oTariffPlan->lots_left = $oTariffPlan->lots_left + 1;
                        $oTariffPlan->save();
                        
                        $oUser = User::model()->with('profile')->findByPk($oTariffPlanBuyLots->user_id);

                        $oEmailNotification = new EmailNotification();
                        $oEmailNotification->sendEmailToUserAfterApproveAdditionalLot($oUser, $oTariffPlan);

                        Yii::app()->user->setFlash('tariff_lots_orders', 'Дополнительный лот для тарифного плана утвержден');
                    }

                    if ( $sDoRequest == 'reject' )
                    {
                        $oTariffPlanBuyLots->status = 'rejected';
                        $oTariffPlanBuyLots->save();

                        $oUser = User::model()->with('profile')->findByPk($oTariffPlanBuyLots->user_id);

                        $oEmailNotification = new EmailNotification();
                        $oEmailNotification->sendEmailToUserAfterDeclineAdditionalLot($oUser);

                        Yii::app()->user->setFlash('tariff_lots_orders', 'Дополнительный лот для тарифного плана отклонен');
                    }

                }
            }

            Yii::app()->controller->redirect(Yii::app()->controller->createUrl('/admin/tariff_lots_orders/pending_list'));
        }

        $oCriteria = new CDbCriteria();
        $oCriteria->addColumnCondition(array('status' => 'pending'));
        $oCriteria->order = 'date_created DESC';

        $oDataProvider = new CActiveDataProvider('TariffPlanBuyLots', array
        (
            'criteria'   => $oCriteria,
            'pagination' => array
            (
                'pageSize' => 100
            )
        ));

        $this->template->oDataProvider = $oDataProvider;
    }
}